package oop.ex2.main;

import java.io.*;
import java.util.*;
import java.util.regex.Matcher;

import oop.ex2.enums.CommentTypes;
import oop.ex2.enums.MethodTypes;
import oop.ex2.enums.VariableTypes;
import oop.ex2.types.Method;
import oop.ex2.types.Variable;

/**
 * 
 * @author DanielShalev
 *
 */
public class Sjavac {
	
	//the source file given by user
	private static File source;
	
	//list of variables from source file
	private static ArrayList<String> variableList=new ArrayList<String>();
	
	//list of valid (checked) variables
	private static HashMap<String, Variable> variableMap=new HashMap<String, Variable>();
	
	//holds every method in the code with string for the name and array list for the methods
	private static HashMap<String,Method> methodMap=new HashMap<String, Method>();
	
	//true if the next line is part o a comment
	private static boolean isInComment=false;
	
	//true if the next line is in a method
	private static boolean isInMethod=false;
	
	//holds the list that we save to a method
	private static ArrayList<String> tempMethodList;
	
	//the temporary method name
	private static String tempMethodName;
	
	
	/**
	 * this method goes over the variables and checks if they are legal
	 * every legal variable is saved to the variables hash map
	 * @throws IllegalCodeException 
	 */
	private static void checkVariables() throws IllegalCodeException{
		//iterator for variableList
		Iterator<String> iter = variableList.iterator();
		
		while(iter.hasNext()){
			String line=iter.next().trim();
			boolean didMatched=false;
			//goes over all variable types and checks if this line matches one of them
			for(VariableTypes type:VariableTypes.values()){
				Matcher matcher=type.getPattern().matcher(line);
				
				if(matcher.matches()){
					System.out.println(matcher.pattern().pattern());
					didMatched=true;
					variableMap.put(matcher.group(2), new Variable(matcher.group(2), matcher.group(3), matcher.group(1)));
			
				}
				
			}
			//if a line didnt match any type of variable throw bad variable argument exception
			if(!didMatched){
				throw new IllegalCodeException();
			}
		}
		
	}
	
	/**
	 * this method gets a line, checks if he contains comments, 
	 * and erase any comment that he find
	 * @param line the line of code to be checked
	 * @return line of code without comments
	 */
	private static String eraseCommentsFromLine(String line){
		String tempLine=line;
		//goes over all of comments types
		for(CommentTypes type:CommentTypes.values()){
			Matcher matcher=type.getPattern().matcher(line);
			
			//erase the line if its a multy line comment
			if(isInComment){
				tempLine="";
			}
			
			
			while(matcher.find()){
				//checks if its a multy line comment start
				if(type.equals(CommentTypes.MULTY_LINES_COMMENT_BEGIN)){
					isInComment=true;
				}
				//checks if its a multy line comment end
				if(type.equals(CommentTypes.MULTY_LINES_COMMENT_END)){
					isInComment=false;
				}				
				
				tempLine=line.replace(matcher.group(), " ");
			}
		}
		return tempLine;
	}
	
	/**
	 * this method gets a line of code and determines if its a method
	 * if its a method we save it to a hash map
	 * @param line the line of code
	 * @throws IllegalCodeException 
	 */
	private static void extractMethods(String line) throws IllegalCodeException{
		int bracketsCount=0;
		if(line.contains("{")){
			bracketsCount++;
		}
		if(line.contains("}")){
			bracketsCount--;
		}
		//checks if we are in the middle of a method and adds a line to the methods array list
		if(isInMethod){
			if(line.contains("}") && bracketsCount==0){
				isInMethod=false;
				return;
			}
			else{
				methodMap.get(tempMethodName).getLines().add(line);
			}
		}
		//goes over method types
		for(MethodTypes type:MethodTypes.values()){
			Matcher matcher=type.getPattern().matcher(line);
			if(matcher.matches()){
				tempMethodName=matcher.group(2);
				isInMethod=true;
				HashMap<String,Variable> arguments=new HashMap<String, Variable>();
				//parse the arguments
				String[] argNames=matcher.group(3).split(",");
				for(String s:argNames){
					
					String[] parseArg=s.trim().split("\\s+");
					if(parseArg.length>2){
						//throw exception
						throw new IllegalCodeException();
					}
					if(parseArg.length>1 ){
						//checks if an argument with the same name exist
						if(arguments.containsKey(parseArg[1])){
							throw new IllegalCodeException();
						}
						arguments.put(parseArg[1], new Variable(parseArg[1], "", parseArg[0]));
					}	
				}
				methodMap.put(tempMethodName, new Method(matcher.group(2),matcher.group(1),arguments,
						new ArrayList<String>()));
			}
			
		}
	}
	
	/**
	 * this method gets a file and parse him to lines saved in an ArrayList of Strings
	 * this method also erase comments 
	 * @param pathName the file to read
	 * @throws IOException 
	 * @return ArrayList of lines from the file
	 * @throws IllegalCodeException 
	 */
	private static void readFile(File pathName) throws IOException, IllegalCodeException{
		//the list of lines to be returned
		ArrayList<String> stList=new ArrayList<String>();
		
		//read the file and assign each line in to a list 
		BufferedReader reader=new BufferedReader(new FileReader(pathName));//the reader for the pathName
		String line=reader.readLine();
		while(line!=null){
			
			//erase comments
			line=eraseCommentsFromLine(line);
			
			//extract to methods
			extractMethods(line);
			
			//extract variables
			if(!isInMethod && !(line.contains("}")) && !(line.isEmpty())){
				variableList.add(line);
			}
			line=reader.readLine();
		}	
		stList.trimToSize();
		
	}
	
	
	
	
	
	
	
	
	
	/**
	 * 
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException{
		try{
			//assign the argument user gave us
			source=new File(args[0]);
			
			//parse the file in to variables and methods
			readFile(source);
			
			//checks if variables are legal
			checkVariables();
			
			//checks if methods are legal
			for(Method method:methodMap.values()){
				CheckMethod checker=new CheckMethod(methodMap, variableMap, method.getName());
				checker.check();
			}
		}
		catch(IOException e){
			System.err.println("ERROR");
			System.exit(2);
		} catch (IllegalCodeException e) {
			e.printStackTrace();
			System.exit(1);
		}
		System.exit(0);
		
	}
}
